package com.qiaoba.module.job.core;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.qiaoba.api.job.constant.JobConstant;
import com.qiaoba.common.base.constant.BaseConstant;
import com.qiaoba.module.job.entity.SysJob;
import com.qiaoba.module.job.entity.SysJobLog;
import com.qiaoba.module.job.service.SysJobLogService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Date;

/**
 * 抽象quartz调用
 *
 * @author ailanyin
 * @date 2023-09-03 23:11:00
 */
@Slf4j
public abstract class AbstractQuartzJob implements Job {

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        SysJob sysJob = (SysJob) context.getMergedJobDataMap().get(JobConstant.TASK_PROPERTIES);
        Date startTime = new Date();
        try {
            doExecute(context, sysJob);
            after(sysJob, startTime, null);
        } catch (Exception e) {
            log.error("执行定时任务异常  - ：", e);
            after(sysJob, startTime, e);
        }
    }

    /**
     * 执行后-记录日志
     *
     * @param sysJob 系统计划任务
     */
    private void after(SysJob sysJob, Date startTime, Exception e) {
        final SysJobLog sysJobLog = new SysJobLog();
        sysJobLog.setJobId(sysJob.getJobId());
        sysJobLog.setJobName(sysJob.getJobName());
        sysJobLog.setJobGroup(sysJob.getJobGroup());
        sysJobLog.setInvokeTarget(sysJob.getInvokeTarget());
        sysJobLog.setStartTime(startTime);
        sysJobLog.setStopTime(new Date());
        long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime();
        sysJobLog.setJobMessage("总共耗时：" + runMs + "毫秒");
        if (e != null) {
            sysJobLog.setStatus(BaseConstant.FAIL);
            // 截取异常堆栈信息前2000字符
            String errorMsg = StrUtil.sub(ExceptionUtil.getMessage(e), 0, 2000);
            sysJobLog.setExceptionInfo(errorMsg);
        } else {
            sysJobLog.setStatus(BaseConstant.SUCCESS);
        }

        // 写入数据库当中
        SpringUtil.getBean(SysJobLogService.class).insert(sysJobLog);
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param sysJob  系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception;

}
